package com.peak.distribution.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorViewResolver;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.peak.spring.boot.core.web.MappingJackson2Converter;

@Configuration
public class SpringMvcConfig extends WebMvcConfigurerAdapter {

	@Autowired(required = false)
	private List<ErrorViewResolver> errorViewResolvers;

	private final ServerProperties serverProperties;

	public SpringMvcConfig(ServerProperties serverProperties) {
		this.serverProperties = serverProperties;
	}

	@Bean
	public HttpMessageConverters customConverters() {
		MappingJackson2Converter jsonConverter = new MappingJackson2Converter();
		return new HttpMessageConverters(jsonConverter);
	}

	@Bean
	public SpringErrorController springErrorController(ErrorAttributes errorAttributes) {
		return new SpringErrorController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers);
	}

	@Bean
	public FilterRegistrationBean indexFilterRegistration() {
		FilterRegistrationBean registration = new FilterRegistrationBean(new OpenEntityManagerInViewFilter());
		registration.addUrlPatterns("/*");
		return registration;
	}
}
